import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Department, DepartmentForm } from '@/types'

export const useDepartmentStore = defineStore('department', () => {
  const departments = ref<Department[]>([
    {
      id: 1,
      name: '裸眼电缆作业中心',
      code: 'WLCC',
      description: '负责裸眼电缆作业相关业务',
      parentId: null,
      level: 1,
      sort: 1,
      status: 'active',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-01 10:00:00'
    },
    {
      id: 2,
      name: '随钻测量作业中心',
      code: 'MWDC',
      description: '负责随钻测量作业相关业务',
      parentId: null,
      level: 1,
      sort: 2,
      status: 'active',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-01 10:00:00'
    },
    {
      id: 3,
      name: '装备技术中心',
      code: 'ETC',
      description: '负责装备技术相关业务',
      parentId: null,
      level: 1,
      sort: 3,
      status: 'active',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-01 10:00:00'
    }
  ])

  // 获取所有部门
  const getAllDepartments = () => {
    return Promise.resolve(departments.value)
  }

  // 根据ID获取部门
  const getDepartmentById = (id: number) => {
    const department = departments.value.find(d => d.id === id)
    return Promise.resolve(department)
  }

  // 创建部门
  const createDepartment = (form: DepartmentForm) => {
    const newDepartment: Department = {
      id: Math.max(...departments.value.map(d => d.id)) + 1,
      ...form,
      level: form.parentId ? 2 : 1,
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString()
    }
    departments.value.push(newDepartment)
    return Promise.resolve(newDepartment)
  }

  // 更新部门
  const updateDepartment = (id: number, form: DepartmentForm) => {
    const index = departments.value.findIndex(d => d.id === id)
    if (index !== -1) {
      departments.value[index] = {
        ...departments.value[index],
        ...form,
        updateTime: new Date().toLocaleString()
      }
      return Promise.resolve(departments.value[index])
    }
    return Promise.reject(new Error('部门不存在'))
  }

  // 删除部门
  const deleteDepartment = (id: number) => {
    const index = departments.value.findIndex(d => d.id === id)
    if (index !== -1) {
      departments.value.splice(index, 1)
      return Promise.resolve(true)
    }
    return Promise.reject(new Error('部门不存在'))
  }

  // 获取部门树形结构
  const getDepartmentTree = () => {
    const buildTree = (parentId?: number): Department[] => {
      return departments.value
        .filter(d => d.parentId === parentId)
        .map(d => ({
          ...d,
          children: buildTree(d.id)
        }))
    }
    return Promise.resolve(buildTree())
  }

  return {
    departments,
    getAllDepartments,
    getDepartmentById,
    createDepartment,
    updateDepartment,
    deleteDepartment,
    getDepartmentTree
  }
})
